# -*- coding: utf-8 -*-
from django_openid.consumer import SessionConsumer
from django_openid.models import UserOpenidAssociation
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth import login
from django.contrib.auth.backends import ModelBackend

class DocspotConsumer(SessionConsumer):
    base_template = 'doc_trans/trans/base.html'
    sreg = ['nickname', 'email', ]
    
    def process_request(self, request):
        super(DocspotConsumer, self).process_request(request)
        if request.openid and not request.user.is_authenticated():
            openid = request.openid.openid
            try:
                associate = UserOpenidAssociation.objects.get(openid = openid)
                backend = ModelBackend()
                user = associate.user
                user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
                login(request, user)
                request.session.modified = True
            except UserOpenidAssociation.DoesNotExist:
                if request.path != reverse('main-openid-account-create'):
                    return HttpResponseRedirect(reverse('main-openid-account-create'))
            